<template>
  <div class="info">
    <KiForm v-bind="formConfig" v-model="formData">
      <template #footer>
        <div class="btns">
          <el-button type="primary" @click="handleSaveClick">保存</el-button>
        </div>
      </template>
    </KiForm>

  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import localCache from '@/utils/cache'
import {formConfig} from './config/form-config'
import KiForm from '@/components/ki-form/KiForm.vue';
import { useLoginStore, useTableStore } from '@/store';
import {getAthleteIdByUserId} from '@/network/login'
import {createAthlete,editeAthlete} from '@/network/register'
const loginStore = useLoginStore()
const tableStore = useTableStore()
const formOrignData:any = {}
const formItems = formConfig.formItems || []
const addCollege = () => {
  const collegeItem = formConfig.formItems.find(item => item.field === 'collegeId')
  if(collegeItem){
    collegeItem.options = tableStore.collegesList.map((item:any) => {
      return {
        value:item.id,
        title:item.name
      }
    })
  }
}
let isWrite = ref(false)
addCollege()
if(Object.keys(loginStore.athleteInfo).length !== 0){
  for(const item of formItems){
    formOrignData[item.field] = loginStore.athleteInfo[item.field]
  }
  isWrite.value = true
}else{
  for(const item of formItems){
    formOrignData[item.field] = ''
  }
  isWrite.value = false
}
const formData = ref(formOrignData)
const handleSaveClick = async () => {
  if(!isWrite.value){
    console.log('create',formData.value);
    await createAthlete({...formData.value,userId:loginStore.userId})
  }else{
    console.log('edite');
    await editeAthlete(loginStore.athleteInfo.athleteId,{...formData.value})
  }
  const res = await getAthleteIdByUserId(loginStore.userId)
  if(res){
    loginStore.athleteInfo = res.data
    localCache.setCache('athleteInfo',res.data)
  }
}


</script>

<style scoped>
.btns{
  text-align: center;
}
</style>